package org.ourgrid.worker.ui.async;

import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.ourgrid.worker.WorkerComponentContextFactory;
import org.ourgrid.worker.WorkerConfiguration;
import org.ourgrid.worker.ui.async.client.WorkerAsyncComponentClient;
import org.ourgrid.worker.ui.async.client.WorkerAsyncInitializer;
import org.ourgrid.worker.ui.async.gui.WorkerGUIMainFrame;
import org.ourgrid.worker.ui.async.model.WorkerAsyncUIModel;

import br.edu.ufcg.lsd.commune.context.ModuleContext;
import br.edu.ufcg.lsd.commune.context.PropertiesFileParser;

public class GridMain extends Thread{

	private static final String WORKERGUI_PROPERTIES = "worker.properties";
	
	public void run(){
		BufferedImage iconImage = null;
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			iconImage = ImageIO.read(Main.class.
					getResourceAsStream("/resources/images/icon.png"));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}


		WorkerAsyncUIModel model = new WorkerAsyncUIModel();
		model.loadProperties();
		WorkerAsyncInitializer.getInstance().setModel(model);
		
		WorkerGUIMainFrame frame = new WorkerGUIMainFrame(iconImage, model);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		model.addListener(frame);
		
		WorkerAsyncComponentClient controller = null;
		try {
			ModuleContext context = new WorkerComponentContextFactory(
					new PropertiesFileParser(WORKERGUI_PROPERTIES)).createContext();
			saveProperties(context);
			
			controller = WorkerAsyncInitializer.getInstance().initComponentClient(context, model);
			
		} catch (Exception cre) {
			JOptionPane.showMessageDialog(null, cre.getMessage(), "Error on worker startup", JOptionPane.ERROR_MESSAGE);
			frame.workerStopped();
			frame.setStartEnabled(false);
			return;
		}
		
		if (controller.getModel().isWorkerUp()) {
			frame.workerStarted();
		} else {
			frame.workerStopped();
		}
	}
	
	private static void saveProperties(ModuleContext context) throws FileNotFoundException, IOException {
		Properties properties = new Properties();
		properties.putAll(context.getProperties());
		properties.store(new FileOutputStream(WorkerConfiguration.PROPERTIES_FILENAME), null);
	}
	
}
